package cn.easyar.samples.helloarqrcode.remote;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.logger.Logger;
import com.udevel.widgetlab.TypingIndicatorView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.easyar.samples.helloarqrcode.MyApplication;
import cn.easyar.samples.helloarqrcode.R;
import cn.easyar.samples.helloarqrcode.adpter.SelectListAdapter;
import cn.easyar.samples.helloarqrcode.bean.UserStatusBean;
import cn.easyar.samples.helloarqrcode.util.GlobalParams;
import cn.easyar.samples.helloarqrcode.xunfei.VoiceBean;
import cn.easyar.samples.helloarqrcode.xunfei.VoiceOrder;
import cn.easyar.samples.helloarqrcode.xunfei.VoiceService;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;

public class SelectListActivity extends BaseActivity {

    @BindView(R.id.rv_user_list)
    RecyclerView rvUserList;
    @BindView(R.id.ib_up_arrow)
    ImageButton ibUpArrow;
    @BindView(R.id.tv_user_list)
    RecyclerView tvUserList;
    @BindView(R.id.ib_down_arrow)
    ImageButton ibDownArrow;
    @BindView(R.id.progress_view)
    TypingIndicatorView progressView;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.btn_cancel)
    Button btnCancel;
    @BindView(R.id.rl_wait_layout)
    RelativeLayout rlWaitLayout;
    @BindView(R.id.btn_back)
    Button btn_back;
    private AgoraAPIOnlySignal mAgoraAPI;
    List<UserStatusBean> userList = new ArrayList<>();
    private SelectListAdapter selectListAdapter;
    private boolean isCall = false;//是否呼叫
    private String guidName;
    private String remoteAccount;
    private String channelName;


    @Override
    public int getLayoutId() {
        return R.layout.activity_select_list;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        initAgoraEngineAndJoinChannel();
        EventBus.getDefault().register(this);
        VoiceOrder.activityList.add("SelectListActivity");
        /*焦点列表*/
        GridLayoutManager manager = new GridLayoutManager(this, 1);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        manager.supportsPredictiveItemAnimations();

        userList.clear();
        userList.add(new UserStatusBean("测试员"));

        selectListAdapter = new SelectListAdapter(userList);
        selectListAdapter.setHasStableIds(true);
        tvUserList.setLayoutManager(manager);
//        DefaultItemAnimator animator = new DefaultItemAnimator();
//        tvUserList.setItemAnimator(animator);
        tvUserList.setItemAnimator(null);
        tvUserList.setAdapter(selectListAdapter);
        tvUserList.setOnScrollListener(new OnPopRecyclerViewScrollListener());
        MyApplication.the().getmAgoraAPI().login2(getString(R.string.agora_app_id), "111111", "_no_need_token", 0, "", 5, 1);
        selectListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                int status = MyApplication.the().getmAgoraAPI().getStatus();
                    UserStatusBean mBean = userList.get(position);
                    isCall = true;
                    guidName = mBean.name;
                    remoteAccount = "666666";
                    tvName.setText(guidName);
                    //查询用户是否在线 todo
                    mAgoraAPI.queryUserStatus(remoteAccount);
                    //展示呼叫等待
                    rlWaitLayout.setVisibility(View.VISIBLE);
                    btnCancel.requestFocus();
                    progressView.stopDotAnimation();
                    progressView.startDotAnimation();
            }
        });
    }

    @Override
    public void loadData() {

    }

    private void initAgoraEngineAndJoinChannel() {
        mAgoraAPI = MyApplication.the().getmAgoraAPI();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void voiceEvent(VoiceBean voiceBean) {
        if(voiceBean.str.contains(VoiceOrder.VOICE_QUIT)&&VoiceOrder.activityList.get(VoiceOrder.activityList.size()-1).equals("SelectListActivity")){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            });
        }else if(voiceBean.str.contains(VoiceOrder.VOICE_EXPERT)){
            int status = MyApplication.the().getmAgoraAPI().getStatus();
            if (status == 2) {//2: 用户已登录。
                UserStatusBean mBean = userList.get(0);
                isCall = true;
                guidName = mBean.name;
                remoteAccount = "666666";
                tvName.setText(guidName);
                //查询用户是否在线 todo
                mAgoraAPI.queryUserStatus(remoteAccount);
                //展示呼叫等待
                rlWaitLayout.setVisibility(View.VISIBLE);
                btnCancel.requestFocus();
                progressView.stopDotAnimation();
                progressView.startDotAnimation();
            } else {
                MyApplication.the().getmAgoraAPI().login2(getString(R.string.agora_app_id), "111111", "_no_need_token", 0, "", 5, 1);
            }
        }
    }

//    private void getUserList() {
//        new RxHttp<BaseResult<List<ExpertUserEnity>>>().send(ApiManager.getService().getExpertList(), new Response<BaseResult<List<ExpertUserEnity>>>(this, true) {
//            @Override
//            public void onNext(BaseResult<List<ExpertUserEnity>> result) {
//                super.onNext(result);
//                if (result.code == 0 && result.data != null) {
//                    userList.clear();
//                    userList.addAll(result.data);
//                    selectListAdapter.notifyDataSetChanged();
//                }
//
//            }
//        });
//    }


    @OnClick({R.id.btn_cancel,R.id.btn_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel://取消呼叫
                isCall = false;
                /*隐藏呼叫等待界面*/
                rlWaitLayout.setVisibility(View.GONE);
                progressView.stopDotAnimation();
                /*取消呼叫 终止成功后主叫方将收到 onInviteEndByMyself() 回调。 */
                callOutHangup();
                break;
            case R.id.btn_back:
                finish();
                break;
        }

    }



    @Override
    protected void onResume() {
        super.onResume();
        addCallback();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        VoiceOrder.activityList.remove(VoiceOrder.activityList.size()-1);
        EventBus.getDefault().unregister(this);
    }

    //结束呼叫
    private void callOutHangup() {
        if (mAgoraAPI != null)
            mAgoraAPI.channelInviteEnd(channelName, remoteAccount, 0);
    }


    //添加信令监听
    private void addCallback() {
        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLogout(final int i) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGOUT_E_KICKED) { // other login the account
                            Logger.i("其他登录帐户，你注销了");

                        } else if (i == IAgoraAPI.ECODE_LOGOUT_E_NET) { // net
                            Logger.i("注销网络不能");

                        }
                        finish();
                    }
                });

            }

            @Override
            public void onLoginFailed(int i) {
                Logger.i("onLoginFailed  i = " + i);
            }



            //当呼叫被对方收到时触发。，本地将回调 onInviteReceivedByPeer, 对方会回调 onInviteReceived。
            @Override
            public void onInviteReceivedByPeer(final String channelID, final String account, int uid) {//call out other local receiver


            }

            //当呼叫被对方接受时触发此回调。
            @Override
            public void onInviteAcceptedByPeer(String channelID, final String account, int uid, String extra) {
                super.onInviteAcceptedByPeer(channelID, account, uid, extra);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Logger.e("===对方确认");
                        rlWaitLayout.setVisibility(View.GONE);
                        progressView.stopDotAnimation();
                        Intent intent = new Intent(SelectListActivity.this, VideoChatViewActivity.class);
                        intent.putExtra("account", account);
                        intent.putExtra("channelName", channelName);
                        intent.putExtra("guidName", guidName);
                        startActivity(intent);
                    }
                });
            }

            @Override
            public void onInviteFailed(String channelID, String account, int uid, int i1, String s2) {
                Logger.i("onInviteFailed  channelID = " + channelID + " account = " + account + " s2: " + s2 + " i1: " + i1);
            }

            @Override
            public void onError(final String s, int i, final String s1) {
                Logger.i("onError s = " + s + " i = " + i + " s1 = " + s1);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (s.equals("query_user_status")) {
                            Logger.i(s1);
                        }
                    }
                });
            }

            //用户状态查询回调 (onQueryUserStatusResult) 1: 用户在线 0: 用户离线
            @Override
            public void onQueryUserStatusResult(final String name, final String status) {
                Logger.i("onQueryUserStatusResult name = " + name + " status = " + status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (status.equals("1")) {
                            //获取房间id 并发起呼叫
                            callInvitation();

                        } else if (status.equals("0")) {
//                            Toasty.info(SelectListActivity.this, "对方处于离线状态", Toast.LENGTH_SHORT, true).show();

                            new Handler().postDelayed(new Runnable(){
                                public void run() {
                                    //execute the task
                                    if (isCall) {
                                        mAgoraAPI.queryUserStatus(remoteAccount);
                                    }
                                }
                            }, 2000);
                        }
                    }
                });
            }

            //结束呼叫 本端会回调 onInviteEndByMyself，对端会回调 onInviteEndByPeer
            @Override
            public void onInviteEndByMyself(String channelID, String account, int uid) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }

            /**
             * 加入信令频道成功
             * @param channelID
             */
            @Override
            public void onChannelJoined(String channelID) {
                super.onChannelJoined(channelID);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //发起呼叫                    成功：自己收到 ICallBack 类的 onInviteAcceptedByPeer() 回调
                        //channelID	频道名。  account 客户端定义的用户账号 uid	固定填 0
                        mAgoraAPI.channelInviteUser(channelName, remoteAccount, 0);
                    }
                });
            }
        });
    }


    /**
     * 获取房间号-----发起呼叫
     */
    private void callInvitation() {
        channelName = "demo111111";
        Logger.i("房间id:"+channelName);
        GlobalParams.savaRoomId(channelName);

        //加入信令频道
        MyApplication.the().getmAgoraAPI().channelLeave(channelName);//离开
        MyApplication.the().getmAgoraAPI().channelJoin(channelName);//加入
    }


    private class OnPopRecyclerViewScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //在滚动的时候处理箭头的状态
//            setUpArrStatus();
//            setDownArrStatus();
        }
    }

    /**
     * 设置上箭头的状态
     */
//    private void setUpArrStatus() {
//        if (tvUserList.isFirstItemVisible()) {
//            ibUpArrow.setVisibility(View.INVISIBLE);
//        } else {
//            ibUpArrow.setVisibility(View.VISIBLE);
//        }
//
//    }

    /**
     * 设置右侧箭头的状态
     */
//    private void setDownArrStatus() {
//        if (tvUserList.isLastItemVisible(1, userList.size())) {
//            ibDownArrow.setVisibility(View.INVISIBLE);
//        } else {
//            ibDownArrow.setVisibility(View.VISIBLE);
//        }
//    }

}
